package com.sziit.se.highconcurrency.common.tool;

import com.sziit.se.highconcurrency.common.exception.NullDataException;
import com.sziit.se.highconcurrency.common.entity.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class LocalUser {

    private LocalUser() {
    }

    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    /**
     * 当前用户加入本地缓存
     *
     * @param user 当前用户
     */
    public static void set(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        LocalUser.threadLocal.set(map);
    }

    public static void clear() {
        LocalUser.threadLocal.remove();
    }

    /**
     * 从本地缓存中获取当前用户
     *
     * @return 当前用户
     */
    public static User getUser() {
        Map<String, Object> map = LocalUser.threadLocal.get();
        if (map == null) {
            return null;
        } else {
            return (User) map.get("user");
        }
    }

    public static User getUserNotNull() {
        return Optional.ofNullable(getUser()).orElseThrow(() -> new NullDataException("LocalUser"));
    }
}
